<?php
class Upload_surat extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('materi_model');
		$this->load->helper(array('form', 'url'));
		$this->load->library('upload');
	}
	
	function index($idkategori)
	{
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['no'] = array('No',40,TRUE,'center',0);
		$colModel['DESKRIPSI'] = array('Deskripsi',300,TRUE,'center',1);
		$colModel['URL_UPLOAD_SURAT'] = array('Link File',200,TRUE,'center',0);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '345',
		'rp' => 10,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Upload File'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$buttons[] = array('Add','add','org_js');
		$buttons[] = array('Delete','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Select All','add','org_js');
		$buttons[] = array('Deselect All','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Back','back','org_js');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("upload_surat/listsurat_grid/".$idkategori),$colModel,'no','asc',$gridParams,$buttons);
		
		if($this->session->flashdata('suc_msg'))
			$data['header_info'] = '<div class="ret_success">'.$this->session->flashdata('suc_msg').'</div>';
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function org_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Add')
				{
					location.href='".base_url()."index.php/upload_surat/input_surat/".$idkategori."'; 
				}
				
				if (com=='Back')
				{
					location.href='".base_url()."index.php/ms_kategori/'; 
				}
				
				if (com=='Delete')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('upload_surat/delete_surat/'.$idkategori)."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			</script>
			";	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
	}
	
	function listsurat_grid($idkategori)
	{
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		
		$valid_fields = array('DESKRIPSI','URL_UPLOAD_SURAT');
		
		$this->flexigrid->validate_post('ID_SURAT','asc',$valid_fields);

		$records = $this->materi_model->get_listsurat($idkategori);
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 0;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			$record_items[] = array($row->ID_SURAT.'#'.$row->URL_UPLOAD_SURAT,
			$no+1,
			'<div align="center">'.$row->DESKRIPSI.'</div>',
			// '<div align="center"><a href="'.base_url().'uploads/file/'.$row->URL_UPLOAD_SURAT.'">'.$row->URL_UPLOAD_SURAT.'</div>',
			'<a href=\''.site_url().'/upload_surat/download_surat/'.$row->ID_SURAT.'/'.$row->URL_UPLOAD_SURAT.'/'.$idkategori.'/\'>'.$row->URL_UPLOAD_SURAT.'</a> ',
			'<a href=\''.site_url().'/upload_surat/edit_surat/'.$row->ID_SURAT.'/'.$idkategori.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> '
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
		
	function cek_validasi() {	
			// Setting Rules
			
			$this->form_validation->set_rules('deskripsi', 'Deskripsi', 'required');
		
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	function input_surat($idkategori)
    {
		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'new';
			// $data['matapelajaran'] = $this->pelajaran_model->get_mp();
			$data['id_kategori'] = $idkategori;
			$data['content'] = $this->load->view('form_upload_surat',$data,true);
			$this->load->view('main',$data);
		}
		else{
			$this->insert_surat($idkategori);
		}            
    }
	
	function insert_surat($idkategori){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		$data = array(
			'DESKRIPSI'			=> $this->input->post('deskripsi'),
			'ID_KATEGORI'		=> $idkategori
		);
		$ins_materi = $this->materi_model->insert_surat($data);
		$getid = $this->materi_model->get_lastid_surat()->row()->lastid;
		$namafile = explode(".",str_replace(' ','_',$_FILES['userfile']['name']));
		$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
		
		if($ins_materi == true){
			$path = './uploads/file/'.$nama_kategori->NAMA_KATEGORI;
			if(!is_dir($path)){ //create the folder if it's not already exists
				mkdir($path,0755,TRUE);
			} 
			if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = $namafile[0];
				// $config['upload_path'] = './uploads/file/';
				$config['upload_path'] = $path;
				$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx|jpg';
				$config['max_size']	= '5000';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['rs_surat'] = $this->materi_model->get_suratID($getid);
					$data['content'] = $this->load->view('form_upload_surat',$data,true);
					$this->load->view('main',$data);
				}
				else {	
						$data2 = array();
						$data2['URL_UPLOAD_SURAT'] = $namafile[0].'.'.$filenamess;
						$this->materi_model->update_surat($data2,$getid);
						
						$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
						redirect('upload_surat/index/'.$idkategori);
					}				
			}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('upload_surat/index/'.$idkategori);
				}
		}
		// $this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
		// redirect('perpus/ms_konfigurasi'); 
	}
	
	function edit_surat($id_surat, $idkategori)
    {
 		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'edit';
				// $data['matapelajaran'] = $this->pelajaran_model->get_mp();
				$data['id_kategori'] = $idkategori;
				$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
				$data['nama_kategori'] = $nama_kategori->NAMA_KATEGORI;
				$data['rs_surat'] = $this->materi_model->get_suratID($id_surat);
				$data['content'] = $this->load->view('form_upload_surat',$data,true);
				$this->load->view('main',$data);
		}
		else{
			$this->update_surat($id_surat, $idkategori);
		}            
    }
	
	function update_surat($id_surat,$idkategori){
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		$data = array(
			'DESKRIPSI'	=> $this->input->post('deskripsi')
		);
		$this->materi_model->update_surat($data,$id_surat);
		$namafile = explode(".",str_replace(' ','_',$_FILES['userfile']['name']));
		$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
		// if($ins_materi == true){
			if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = $namafile[0];
				$config['upload_path'] = './uploads/file/'.$nama_kategori->NAMA_KATEGORI;
				$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx|jpg';
				$config['max_size']	= '5000';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				if($this->input->post('fileold')!= ''){
					unlink('uploads/file/'.$nama_kategori->NAMA_KATEGORI.'/'.$this->input->post('fileold'));
				}
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['id_kategori'] = $idkategori;
					$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
					$data['nama_kategori'] = $nama_kategori->NAMA_KATEGORI;
					$data['rs_surat'] = $this->materi_model->get_suratID($id_surat);
					$data['content'] = $this->load->view('form_upload_surat',$data,true);
					$this->load->view('main',$data);
				}
				else {	
					$data2 = array();
					$data2['URL_UPLOAD_SURAT'] = $namafile[0].'.'.$filenamess;
					$this->materi_model->update_surat($data2,$id_surat);
					
					$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('upload_surat/index/'.$idkategori);
				}				
			}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('upload_surat/index/'.$idkategori);
				}
		// }
	}
	
	//Delete
	function delete_surat($idkategori)
	{
		$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
		$ta_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($ta_ids_post_array as $index => $ta_id){
			if (isset($ta_id) && $ta_id != "") {
				$exp_nama = explode("#",$ta_id);
				// $this->materi_model->delete_surat($ta_id);
				$this->materi_model->delete_surat($exp_nama[0]);
				unlink('uploads/file/'.$nama_kategori->NAMA_KATEGORI.'/'.$exp_nama[1]);		
			
			$msg .= "Data upload file berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
    
	function deletefile($id_surat,$namafile, $idkategori){
		//delete files //
		$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
		if($namafile!= ''){
			unlink('uploads/file/'.$nama_kategori->NAMA_KATEGORI.'/'.$namafile);
			
			$data = array(
				'URL_UPLOAD_SURAT'	=> ''
			);
			$this->materi_model->update_surat($data,$id_surat);
		
			$data['status'] = 'edit';
			$data['id_kategori'] = $idkategori;
			$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
			$data['nama_kategori'] = $nama_kategori->NAMA_KATEGORI;
			$data['rs_surat'] = $this->materi_model->get_suratID($id_surat);
			$data['content'] = $this->load->view('form_upload_surat',$data,true);
			$this->load->view('main',$data);
		}
	}
	
	function download_surat($id, $link, $idkategori){
		$nama_kategori = $this->materi_model->get_namakategori($idkategori)->row();
		$data = array(
			'ID_SURAT'		=> $id,
			'JML_DOWNLOAD'	=> 1,
			'DOWNLOADER'	=> $this->session->userdata('userid'),
			'DOWNLOAD_TIME' => date('Y-m-d H:i:s')
		);
		$this->materi_model->insert_history_surat($data);
		redirect(base_url().'uploads/file/'.$nama_kategori->NAMA_KATEGORI.'/'.$link);
	}
}
?>
